package blog.aop;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import blog.dto.TotalInfo;
import blog.entity.Category;
import blog.entity.Menu;
import blog.entity.Options;
import blog.entity.Tag;
import blog.enums.LinkStatus;
import blog.service.ArticleService;
import blog.service.CategoryService;
import blog.service.CommentService;
import blog.service.LinkService;
import blog.service.MenuService;
import blog.service.TagService;
import blog.utils.DataMapUtil;

/**
 * 在请求处理之前执行，该方法主要是用于准备通用的资源数据
 * 要注意,让它们起作用,要在spring-mvc.xml 中配置对哪些请求进行过滤
 */
@Component
public class CommonDataInterceptor implements HandlerInterceptor {
	
	//文章
	@Resource
	ArticleService articleService;
	
	//分类
	@Resource
	CategoryService categoryService;
	
	//评论
	@Resource
	CommentService commentService;
	
	//标签
	@Resource
	TagService tagService;
	
	//链接
	@Resource
	LinkService linkService;
	
	//菜单
	@Resource
    private MenuService menuService;
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
		//获得网站概况(这些数据时实性比较强,所以放在这里了)	
		TotalInfo totalInfo=new TotalInfo();
		totalInfo.setArticleCount(articleService.countArticle());
		totalInfo.setArticleViewCount(articleService.countArticleView());
		totalInfo.setCategoryCount(categoryService.countCategory() );
		totalInfo.setCommentCount(commentService.countComment());
		totalInfo.setLinkCount(linkService.countLink(LinkStatus.NORMAL.getValue()) );
		totalInfo.setTagCount(tagService.countTag());
        totalInfo.setLastUpdateTime(new SimpleDateFormat("yyyy年MM月dd日").format(articleService.getLastUpdateArticle().getArticleUpdateTime()));    
        request.setAttribute("totalInfo", totalInfo);
        
        //菜单显示
        List<Menu> menuList = menuService.listMenu();
        request.setAttribute("menuList", menuList);
        
        //分类信息(在framework.jsp中做的显示,用于呈现导航, 正常来说,要限定一下查出来的数量,以免前台挤不下,但本查询暂时没做限定))
        List<Category> categoryList = categoryService.listCategory();
        request.setAttribute("cateList", categoryList);
        
        //侧边栏显示所有标签
        List<Tag> tagList = tagService.listTag();
        request.setAttribute("tagList", tagList);
        
        Options options=(Options)DataMapUtil.getObject(DataMapUtil.TEST_LIST, Options.class);
        request.setAttribute("options", options);
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}
}
